<?php

namespace App\Http\Controllers\Home;

use App;

//use Cache;
//use Agent;
use App\Model\Tag;

//use App\Model\Chat;
use App\Model\Article;
use App\Model\ArticleType;

//use App\Model\Category;
use App\Model\ArticleComment;
use App\Model\Zan;
use App\Model\TimeLine;
use App\Model\OauthUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Elasticsearch\ClientBuilder;

//use App\Http\Requests\Comment\Store;
//use Illuminate\Support\Facades\Validator;
//use Illuminate\Support\Facades\Auth;
use Auth;

//use Illuminate\Support\Facades\Redirect;
use App\User;

//use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use App\library\Tree;
use Illuminate\Support\Facades\Cache;

class IndexController extends Controller
{
    public $title = 'Agoni个人技术文章';
    public $des = '本站主要分享IT相关干货,涉及到前端后端全栈相关技能知识点其中包含,git管理工具使用,swoole基础运用或客服系统教学,redis,php,mysql,nginx等php常用开发服务,分享内容时请标注转发链接,该站主要为了交友、分享、学习为一体的博客站 请记住Agoni这个单词 也是我印象最深的词';
    public $key = '';

    public function __construct()
    {

//        $d=get_cookie('is_scrapy');
//        $this->key=md5( get_ip().strtotime(date("Y-m-d")));
//        if(empty($d)){
//            set_cookie("is_scrapy",$this->key,60*60*24);
//        }elseif($d!=$this->key){
//            set_cookie("is_scrapy",$this->key,60*60*24);
//        }
        //最新
        $data = Cache::get('blog_common:index', function () {
            $type_all = ArticleType::select('id', 'title')->get();
            //热门推荐
            $hot_article = Article::select('id', 'title')->where(['is_delete' => 0])->OrderBy('click', 'desc')->limit(8)->get();
            //随便看看 随机显示数据
            $author_article = Article::select('id', 'title')->where(['openness' => 1])->limit(8)->inRandomOrder()->get();

            $data['type_all'] = $type_all;
            $data['hot_article'] = $hot_article;
            $data['author_article'] = $author_article;
            Cache::put('blog_common:index', $data, 24 * 60);
            return $data;
        });

        //标题
        $title = $this->title;
        $type_all = $data['type_all'] ?? [];
        $hot_article = $data['hot_article'] ?? [];
        $author_article = $data['author_article'] ?? [];
//        $type_all = ArticleType::select('id', 'title')->get();
//        //热门推荐
//        $hot_article = Article::select('id', 'title')->where(['is_delete'=>0])->OrderBy('click', 'desc')->limit(8)->get();
//        //随便看看 随机显示数据
//        $author_article = Article::select('id', 'title')->where(['openness' => 1])->limit(8)->inRandomOrder()->get();

        view()->composer(['home.article.index', 'home.category.index', 'home.article.detail', 'home.tag.index'], function ($view) use ($type_all, $hot_article, $author_article, $title) {
            $view->with('type_all', $type_all);
            $view->with('hot_article', $hot_article);
            $view->with('author_article', $author_article);
            //$view->with('user',array('name'=>'test','avatar'=>'/path/to/test.jpg'));
        });
    }

    public function push(Request $request)
    {


//        $this->checkScrapy();
//        die('11');
//        Cache::flush();
        $urls = array(

            'https://www.agoni.top/article/detail/3',
            'https://www.agoni.top/timeline',
            'https://www.agoni.top/article/detail/4',
            'https://www.agoni.top/article/detail/5',
            'https://www.agoni.top/article/detail/6',
            'https://www.agoni.top/article/detail/7',
            'https://www.agoni.top/article/detail/8',
            'https://www.agoni.top/article/detail/9',
            'https://www.agoni.top/article/detail/10',
            'https://www.agoni.top/article/detail/11',
            'https://www.agoni.top/article/detail/12',
            'https://www.agoni.top/article/detail/13',
            'https://www.agoni.top/article/detail/14',
            'https://www.agoni.top/article/detail/15',
            'https://www.agoni.top/article/detail/16',
            'https://www.agoni.top/article/detail/17',
            'https://www.agoni.top/article/detail/18',
            'https://www.agoni.top/article/detail/19',
        );
        $api = 'http://data.zz.baidu.com/urls?site=https://www.agoni.top&token=rl4zkpr6igP591RC';
        $data1 = $this->pushRequest($api, $urls);
        //解析站
        $api = 'http://data.zz.baidu.com/urls?site=https://www.agoni.top&token=rl4zkpr6igP591RC';
        $urls = [
            'https://vip.agoni.top'
        ];
        $api = 'http://data.zz.baidu.com/urls?site=https://vip.agoni.top&token=rl4zkpr6igP591RC';
        $data2 = $this->pushRequest($api, $urls);
        return ['data1' => $data1, 'data2' => $data2];
    }

    public function pushRequest($api, $urls)
    {
        $ch = curl_init();
        $options = array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }

    /**
     * 首页
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function index(Request $request)
    {
//        dd($this->push());
        $page = $request->input('page', 1);
        //置顶
        $top_article = Cache::get('top_article:index', function () {
            $top_article = Article::select('*')
                ->where('is_top', '=', '1')
                ->where('is_delete', '=', '0')
                ->orderBy('created_at', 'desc')
                ->limit(3)
                ->with(['tags'])
                ->withCount(['comments', 'zans' => function ($query) {
                    $query->where(['type' => 1]);
                }])
                ->get();
            Cache::put('top_article:index', $top_article, 24 * 60);
            return $top_article;
        });
        //最新
        $article = Cache::get('new_article:index' . $page, function () use ($page) {
            $article = Article::select('*')
                ->where('is_delete', '=', '0')
                ->where('openness', '=', '1')
                ->orderBy('created_at', 'desc')
                ->limit(5)
                ->with('tags')
                ->withCount(['comments', 'zans' => function ($query) {
                    $query->where(['type' => 1]);
                }])
                ->paginate();
            Cache::put('new_article:indexa' . $page, $article, 24 * 60);
            return $article;
        });

        $data = Cache::get('blog_index:common', function () {
            //热门推荐
            $hot_article = Article::select('id', 'title')->where('is_delete', '=', 0)->OrderBy('click', 'desc')->limit(8)->get();
            $author_article = Article::select('id', 'title')->where(['openness' => 1, 'is_delete' => 0])->OrderBy('created_at', 'desc')->limit(8)->get();
            //友情链接
            $friendshiplink = App\Model\FriendshipLink::limit(5)->get();
            //最新评论
            $comment = ArticleComment::select('id', 'article_id', 'user_id', 'content')->with(['users', 'articles'])->limit(8)->orderBy('created_at', 'desc')->get();

            //最新留言
            $message = App\Model\Message::select('id', 'uid', 'title')->with(['users'])->limit(8)->orderBy('created_at', 'desc')->get();
            //博客数
            $article_count = Article::count();
            //评论数
            $comment_count = ArticleComment::count();
            //留言数
            $message_count = App\Model\Message::count();
            //分类
            $category = ArticleType::get();
            //通知
            $notices = App\Model\Notice::get();
            //轻言细语
            #time
            $timeLines = TimeLine::query()->get();

            $data = compact(
                'timeLines', 'notices', 'hot_article', 'friendshiplink', 'comment', 'message', 'article_count', 'comment_count', 'message_count', 'category', 'author_article');

            Cache::put('blog_index:common', $data, 60 * 24);

            return $data;
        });

        $data['article'] = $article;
        $data['top_article'] = $top_article;

        return view('home.index.index', $data);
    }

    /**
     * 全部文章
     */
    public function all(Request $request, Article $article)
    {
        //文章展示


        $page = $request->input('page', 1);
        $page_size = $request->input('limit', 5);
        $search = $request->input('keywords');
        $query = Article::select('*');
        //搜索
        if (!empty($search)) {
            //->paginate()
            $id = $article->searchArticleGetId($search);
            $query->whereIn('id', $id);
        }
        $article_count = $query->count();
        $pages = ceil($article_count / $page_size);
        //分页
        if (empty($page)) {
            $page = 1;
        }
        $page_count = ($page - 1) * $page_size;
        if ($article_count < $page_size) {
            $page_size = $article_count;
        }
        $query->offset($page_count)->limit($page_size);

        $article_all = Cache::get('article_page_' . $page . 'size_' . $page_size . ':all', function () use ($query, $page) {
            $article_all = $query->orderBy('created_at', 'desc')
                ->where(['is_delete' => 0])
                ->where('openness', '=', '1')
                ->with(['tags'])
                ->withCount(['comments', 'zans' => function ($query) {
                    $query->where(['type' => 1]);
                }])->get();

            Cache::put('article_page' . $page . ':all', $article_all, 60 * 24);
            return $article_all;
        });


        $data = compact('article_all', 'pages', 'page');

        return view('home.article.index', $data);
    }

    /**
     * 文章详情
     * @return \Illuminate\Contracts     * @param $id\View\Factory|\Illuminate\View\View
     */
    public function detail($id, Zan $zan)
    {

        //记录阅读数
        $article = Article::where(['is_delete' => 0])->find($id);
        if (empty($article)) {
            abort(404);
            return redirect()->back();
        }
        $data = $article;
        //判断该ip是否访问过
        if (!$zan->isClick($id)) {
            $article->click = $article->click + 1;
            $click_number = $article->click;
            $article->save();
            $data->click = $click_number;
        }
        //获取文章分类
        $type = ArticleType::find($article->type_id);
        $zan_count = Zan::where('type', '=', 1)->where(['article_id' => $id])->count();
        $key = 'article_detail_' . $id;
        $comment_list1 = Cache::get($key, function () use ($id, $key) {
            //获取评论这一块是为了学习递归而采用这种模式 性能不好 可以更改下数据库结构重构这边
            $comment_list = ArticleComment::select('id', 'user_id', 'content', 'pid', 'created_at')->where('article_id', '=', $id)
                ->with(['users'])->orderBy('created_at', 'desc')->get()->toArray();
            //一级评论
            $parent_ids = [];//一级评论索引数组
            $comment_list1 = [];//评论数组
            if (!empty($comment_list)) {
                foreach ($comment_list as $item => $value) {
                    //获取被回复者用户 只有在pid不等于0时有效
                    if ($value['pid'] != 0) {
                        $id = ArticleComment::find($value['pid'])['user_id'];
                        $users = User::find($id)->toArray();
                        $comment_list[$item]['by_reply_user'] = $users;
                    } else {
                        $parent_ids[] = $item;
                    }
                }
            }
            //获取评论子集
            foreach ($parent_ids as $item => $value1) {
                $comment_list1[$item] = $comment_list[$value1];
                $comment_list1[$item]['child'] = (new Tree())->getInvId($comment_list, $comment_list[$value1]['id']);
                arraySort($comment_list1[$item]['child'], 'id', SORT_ASC);
            }
            Cache::put($key, $comment_list1, 60 * 24);
            return $comment_list1;
        });
        $desc = $article->title . strip_tags($article->content);
        $title = $article->title ?? $this->title;

        return view('home.article.detail', ['title' => $title . " - Agoni技术文章", 'desc' => $desc, 'article' => $data, 'comment_list' => $comment_list1, 'type' => $type, 'zan_count' => $zan_count]);
    }

    /**
     * 获取分类下的文章
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|void
     */
    public function category($id)
    {

        $types = ArticleType::select('id', 'title')->where('id', '=', $id)->first();

        $article_all = $types->articles()
            ->orderBy('created_at', 'desc')
            ->with('tags')
            ->withCount(['comments', 'zans'])->paginate();
        $title=($types->title ?? $types->title) . ' - Agoni技术文章';
        return view('home.category.index', ['article_all' => $article_all, 'types' => $types,'title'=>$title]);
        //return view('home.index.index',['articles'=>$articles]);
    }

    /**
     * 获取标签下的文章
     *
     * @param $id
     *
     * @return \Illuminate\Contracts\View\Factory
     */
    public function tag($id, Request $request, Article $article)
    {

        $search = $request->input('search');

        $tags = Tag::select('id','name')->where('id', '=', $id)->first();

        if (!$tags) {
            abort(404);
        }

        $query = Article::select('*');
        //搜索
        if (!empty($search)) {
            //->paginate()
            $ids = $article->searchArticleGetId($search);
            $query->whereIn('id', $ids);
        }
        $article_all = $tags->articles()->paginate();;
        $title=($tags->name ?? $tags->name) . ' - Agoni技术文章';

        $data = compact('article_all','title');

        return view('home.tag.index', $data);


    }

    /**
     * 随言碎语
     *
     * @return mixed
     */
    public function timeline()
    {
        $time_line = TimeLine::query()->orderby("id", "desc")->get();
        return view('home.timeline.index', ['title' => "点点滴滴" . " - Agoni技术文章", 'time_line' => $time_line]);
    }

    /**
     * 开源项目
     *
     * @return mixed
     */
    public function production()
    {
        $git_project = App\Model\GitProject::query()->orderBy('sort', 'desc')->get();
        return view('home.production.index', ['title' => "开源项目列表" . " - Agoni技术文章", 'git_project' => $git_project]);
    }

    /**
     * 文章评论
     *
     * @param Store $request
     * @param Comment $commentModel
     * @param OauthUser $oauthUserModel
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function comment(Request $request)
    {
        if ($request->isMethod('post')) {
            if (!Auth::check()) {
                return respone_return(0, '请先登陆');
            }
            //$uid=Auth()->user()->id;
            $uid = Auth::guard('web')->user()->id;
            $article_id = $request->input('article_id');
            $comment = $request->input('comment');
            $pid = $request->input('pid');

            $article_comment = new ArticleComment();
            $article_comment->user_id = $uid;
            $article_comment->article_id = $article_id;
            $article_comment->content = $comment;
            $data = [];
            if (!empty($pid)) {
                $article_comment->pid = $pid;
            } else {
                $article_comment->pid = 0;
            }
            if ($article_comment->save()) {
                $key = 'article_detail_' . $article_id;
                Cache::forget($key); //清楚缓存
                return respone_return(200, '发表成功');
            } else {
                return respone_return(0, '发表失败');
            }

        }
        return view('home.comment.index');
    }

    public function about()
    {


        //友情链接
        $friendshiplink = App\Model\FriendshipLink::limit(5)->get();

        return view('home.about.index', ['title' => "个人主页", 'friendshiplink' => $friendshiplink]);
    }


    /**
     * 搜索文章
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function search(Request $request)
    {
        $wd = $request->input('query');

        $article = Article::select(
            'title', 'keywords', 'is_top',
            'zan', 'click', 'tag_ids', 'created_at'
        )->orWhere('keywords', 'like', "%$wd%")
            ->orWhere('content', 'like', "%$wd%")
            ->orWhere('title', 'like', "%$wd%")
            ->with('tags')
            ->get();
        return view('home.index.index');
    }

    /**
     *点赞
     */
    public function zan(Request $request)
    {
        if ($request->isMethod('post')) {
            $article_id = $request->input('article_id');
            $article = Article::find($article_id);
            if (empty($article)) {
                return abort(403, '文章不存在');
            }
            $ip = get_ip();
            $zan = Zan::where('ip', '=', $ip)->where('article_id', '=', $article_id)->where('type', '=', 1)->first();
            if (empty($zan)) {
                //如果查不到该ip则进行ip记录
                $model = new Zan();
                $model->ip = $ip;
                $model->article_id = $article_id;
                $model->type = 1;
                $model->save();
                //对文章进行点赞次数累加
                $article = Article::find($article_id);
                $article->zan = $article->zan + 1;
                $article->save();
                return respone_return(200, '点赞成功');
            } else {
                return respone_return(0, '请不要进行重复点赞');
            }
        }
    }

    /**
     * 邮箱功能
     * @return \Illuminate\Http\JsonResponse
     */
    public function send()
    {
        $ip = get_ip();
        dd($ip);
        send_email(0);

//        $name='杨先生';
//        $data = ['email'=>'544867814@qq.com', 'name'=>$name,'uid'=>123,'activationcode'=>mt_rand(100000,999999)];
//        try{
//            Mail::send('home.email', $data, function($message) use($data)
//            {
//                $message->to($data['email'], $data['name'])->subject('欢迎注册我们的网站，请激活您的账号！');
//            });
//        }catch (\Exception $e){
//            dd($e->getMessage());
//        }

        die('11');
//        $flag= Mail::raw('你好，我是PHP程序！',function($message) {
//
//            $to='544867814@qq.com';
//
//            $message->to($to)->subject('纯文本信息邮件测试');
//
//        });
//
//        if(!$flag){
//
//            echo '发送邮件成功，请查收！';
//
//        }else{
//
//            echo '发送邮件失败，请重试！';
//
//        }
        return respone_return(0, '成功');
    }

    /**
     * 获取用户真实 ip
     * @return array|false|mixed|string
     */
    function getClientIp()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        if (getenv('HTTP_X_REAL_IP')) {
            $ip = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
            $ips = explode(',', $ip);
            $ip = $ips[0];
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = '0.0.0.0';
        }

        return $ip;
    }

    public function isValidUrl($url)
    {
        return preg_match('/^http[s]?:\/\/' .
                '(([0-9]{1,3}\.){3}[0-9]{1,3}' . // IP形式的URL- 199.194.52.184
                '|' . // 允许IP和DOMAIN（域名）
                '([0-9a-z_!~*\'()-]+\.)*' . // 域名- www.
                '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.' . // 二级域名
                '[a-z]{2,6})' .  // first level domain- .com or .museum
                '(:[0-9]{1,4})?' .  // 端口- :80
                '((\/\?)|' .  // a slash isn't required if there is no file name
                '(\/[0-9a-zA-Z_!~\'
\.;\?:@&=\+\$,%#-\/^\*\|]*)?)$/',
                $url) == 1;
    }

    public function showImg()
    {

        $URL = $_GET["cache"] ?? '';
        if (!$this->isValidUrl($URL)) {
            echo "转接的URL不合法呢~";
            exit;
        }
        $Host = getHost($URL);

        if (empty($_GET["referer"])) $referer = $Host;

        //echo $_GET["cache"];
        $hdrs = array(
            'http' => [
                'method' => 'GET',
                'header' => [
                    "Accept:image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
                    "Host:www.acganime.com",
                    "Referer: http://www.acganime.com/",
                    "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
                ],
                'timeout' => 5
            ],
        );
        $context = stream_context_create($hdrs);
        return response()->stream(function () use ($URL, $context) {
            return file_get_contents("https://www.agoni.top/1.jpg");

        }, 200, ['Content-Type' => 'image/jpeg']);

    }

    public function replace($search, $replace)
    {
        $all = Article::query()->where('content', 'like', "%$search%")->get();
//        $search="cache=https://www.agoni.top/show/img?cache=https://www.agoni.top/show/img?cache=http://www.acganime.com";
//        $replace='cache=http://www.acganime.com';
        foreach ($all as $item => $value) {
            try {
                dd($value);
                $value->cover = str_replace($search, $replace, $value->cover);
                $value->content = str_replace($search, $replace, $value->content);
                $value->markdown = str_replace($search, $replace, $value->markdown);

                $value->save();
            } catch (\Throwable  $e) {
                dd($e->getMessage());
            }
        }
    }


    //redis测试练习
    public function test()
    {

        DB::disconnect();

        \Config::set("database.connections.mysql", [
            'driver' => 'mysql',
            "host" => "mysql",
            'port' => '3306',
            "database" => "raccoon5",
            "username" => "root",
            "password" => "root"
        ]);
        $all = DB::table('tp_book')->where('cover_url', 'like', '%m.dmzj.com%')->get();

        foreach ($all as $item) {
            $cover = str_replace("m.dmzj.com", "images.dmzj.com", $item->cover_url);
            DB::table('tp_book')->where(['id' => $item->id])->update(['cover_url' => $cover]);
        }
        dd('成功');

        $this->replace('src="https://www.agoni.top', 'src="https://www.agoni.top');


        die('112');
        $all = Article::query()->where('cover', 'like', '%http://www.acganime.com%')->get();


        $all = Article::query()->where('cover', 'like', '%http://www.acganime.com%')->get();
        $search = "http://www.acganime.com";
        $replace = 'https://www.agoni.top/show/img?cache=http://www.acganime.com';

//        $search="cache=https://www.agoni.top/show/img?cache=https://www.agoni.top/show/img?cache=http://www.acganime.com";
//        $replace='cache=http://www.acganime.com';
        foreach ($all as $item => $value) {
            try {
                $value->cover = str_replace($search, $replace, $value->cover);
                $value->content = str_replace($search, $replace, $value->content);
                $value->markdown = str_replace($search, $replace, $value->markdown);
                $value->save();
            } catch (\Throwable  $e) {
                dd($e->getMessage());
            }


        }

        dd('11');


        $content = "https://www.agoni.top/show/img?cache=https://www.agoni.top/show/img?cache=https://www.agoni.top/show/img?cache=http://www.acganime.com/wp-content/uploads/2022/05/445729613116-480x340.png";
        $search = "cache=https://www.agoni.top/show/img?cache=https://www.agoni.top/show/img?cache=http://www.acganime.com";
        $replace = 'cache=http://www.acganime.com';
//        echo str_replace($search,$replace,$content);die;
//
//
//        $search="http://www.acganime.com";
//        $replace='https://www.agoni.top/show/img?cache=http://www.acganime.com';

        try {
            $value = Article::find(530);
            $value->cover = str_replace($search, $replace, $value->cover);
            $value->content = str_replace($search, $replace, $value->content);
            $value->markdown = str_replace($search, $replace, $value->markdown);
            dd($value);
//            foreach ($all as $item=>$value){
//
//                $value->save();
//            }
        } catch (\Throwable  $e) {
            dd($e);
        }


        $all = Article::query()->where('cover', 'like', '%http://www.acganime.com%')->get();
        $search = "http://www.acganime.com";
        $replace = 'https://www.agoni.top/show/img?cache=http://www.acganime.com';
        foreach ($all as $item => $value) {
            try {
                $value->cover = str_replace($search, $replace, $value->cover);
                $value->content = str_replace($search, $replace, $value->content);
                $value->markdown = str_replace($search, $replace, $value->markdown);
            } catch (\Throwable  $e) {
                dd($e->getMessage());
            }

            dd($value);
        }


        return $this->showImg();
        dd($this->getClientIp());
        $command = "echo 111";
        echo exec($command);
        die;
        $path = __DIR__ . '/3.PDF';
        $path3 = __DIR__ . '/11.jpg';
        $pdf = new \Spatie\PdfToImage\Pdf($path);
        $pdf->setPage(1);
        $pdf->saveImage($path3);
        die;


        $img = $this->Pdf2Jpeg($path, true, $path3);
        echo $img;
        die;
//        $imgArr = Handler::pdfToPng($path,$_SERVER['DOCUMENT_ROOT'].'/file/');
//
//        $img = '';
//
//        if($imgArr&&is_array($imgArr)){
//
//            $img = Handler::spliceImg($imgArr,$_SERVER['DOCUMENT_ROOT'].'/file/agreement/');
//
//        }
//        dd($img);
//
//        dd(curl('http://www.test10.com/comment', 'POST', ['username' => 'yangbangcheng', 'password' => '123456']));
//        die;
        try {
            $arr = [1, 22, 33, 4, 55, 66, 76, 78];//一维数组
            $str = 'hello word';
            $int = 520;
            $repetition = ['1', '2', '1', '3', '2', '5'];//带有重复的数组
            $user = ArticleComment::all(); //数组
            Redis::del('key');

            //测试一 普通键值
            Redis::set('key', $user);
            $values = json_decode(Redis::get('key'), true);

            //测试二
            if (Redis::exists('key')) {
//                echo '32';
//
//               echo Redis::del('foo'); // 成功删除返回 true, 失败则返回 false
//                dd(Redis::get('key'));
            }

            Redis::rpush('tab', $repetition);
            Redis::rpush('tab', 2);
            Redis::rpush('tab', 17);
            //dd(Redis::sort('tab',array('sort' => 'desc')));
            Redis::sort('tab', array('limit' => array('alpha' => true)));  //按首字符排序返回array(17,2,3)，因为17的首字符是'1'所以排首位置
            Redis::sort('tab', array('limit' => array('store' => 'ordered')));  //表示永久性排序，返回元素个数
            Redis::sort('tab', array('limit' => array('get' => 'pre_*')));  //使用了通配符'*'过滤元素，表示只返回以'pre_'开头的元素
            //哈希测试
            Redis::hmset('hash1', array('key3' => 'v3', 'key4' => 'v4'));
            Redis::hset('hash1', 'c', 'b');
//            Redis::hmset('hash1',$user);
//            Redis::hmset('hash1',$arr);
            Redis::hmset('hash1', array('a' => 1, 'b' => 2));
            // Redis::hdel('hash1','c');
            Redis::hmget('hash1', ['c', 'b']);
            echo Redis::hlen('hash1');//返回哈希总元素
            echo '<pre>';
            print_r(Redis::hkeys('hash1'));
            print_r(Redis::hvals('hash1')); // 返回 array('v1','v2','v3','v4',13)
            dd(Redis::hgetall('hash1'));//返回整个hash表数据

//            if(Redis::hexists('hash1')){
//                dd(Redis::hmget('hash1'));
//            }
            //测试三 集合的使用
            $key = 'posts_title';
            foreach ($user as $item => $value) {
                Redis::sadd($key, $value);
            }
            Redis::sadd($key, 'abc');
//            Redis::sadd($key,$arr);
            $count = Redis::scard($key);
            if ($count > 0) {
                //Redis::srem($key,'abc');//移除指定元素
                //Redis::spop($key);
                //dd(Redis::smembers($key));
//                Redis::persist($key);//设置为永久 永久存储为-1
//                Redis::expire($key,10);//设置超时时间
//
//                echo Redis::ttl($key); //获取时效
//                Redis::delete('test'); //删除某个键
//                dd(Redis::smembers($key)); //取出所有数据
                //dd(Redis::srandmember($key,25));//从集合中随机取三条
                //dd(Redis::dbsize());//返回redis记录总数
            } else {
                echo '32';
                die;
            }
            //存储多个key测试
            $mkv = array(
                'usr:0001' => 'First user',
                'usr:0002' => 'Second user',
                'usr:0003' => 'Third user'
            );
            Redis::mset($mkv);
            //dd(Redis::get('usr:0001'));//取出单个数据
            //dd(Redis::mget(array_keys($mkv)));//取出多个数据
            //队列测试
            //echo 'rpush:'. Redis::rpush('foolist','bar1');//插入队列的尾部
            //echo 'lpush:'. Redis::lpush('foolist','bar2');//插入队列的头部
            //echo 'rpushx:'.Redis::rpushx('foolist1','bar3');//插入队列的尾部必须是在队列存在时有效

            //echo Redis::llen('foolist');//获取队列的列表长度
            //dd(Redis::lrange('foolist',0,5));//取出0-5区间的列表数据

            //dd(Redis::lindex('foolist',1));//取出指定序列的数据
            Redis::lset('foolist', 1, json_encode($arr));//修改指定序列的值
            //echo '<pre>'; print_r(Redis::lrange('foolist',0,5));

            //队列删除
            Redis::lrem('foolist', 1, '_');// 删除队列中左起(右起使用-1) 1个 字符'_'(若有)
            Redis::lpop('foolist');//删除头部数据
            Redis::rpop('foolist');//删除尾部数据
            //dd(Redis::lrange('foolist',0,5));die;
            //die;
            //有序set表
            Redis::zadd('zset1', 1, 'ab');
            Redis::zadd('zset1', 2, 'cd');
            Redis::zadd('zset1', 3, 'ef');
            //删除指定元素
            Redis::zrem('zset1', 'ef');
            Redis::zremrangebyscore('zset1', 0, 2); // 删除索引在0-2之间的元素('ab','cd'), 返回删除元素个数2
            Redis::zremrangebyrank('zset1', 0, 10);//删除位置为0-10的元素,返回删除的元素个数2
            dd(Redis::zrange('zset1', 0, 3));
//            Redis::zscore()
            //Redis::set("test",'323');
//            Redis::delete('test');
//            Redis::setnx("test",$str);
//            dd(Redis::get('test'));

        } catch (\Exception $e) {
            echo '<br/>行号:' . $e->getLine();
            dd($e->getMessage());
        }
    }

    public function checkScrapy()
    {
        $user_agent = strtolower(\request()->header("user-agent"));
        $user_agent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) ";
        dd(is_spider($user_agent));




        if (strpos($user_agent, 'iask') !== false) {
            return true;
        } elseif (strpos($user_agent, 'yahoo') !== false) {
            return true;
        } elseif (strpos($user_agent, 'bing') !== false) {
            return true;
        } elseif (strpos($user_agent, 'sogou.com') !== false) {
            return true;
        } elseif (strpos($user_agent, 'yodao') !== false) {
            return true;
        } elseif (strpos($user_agent, 'msn.com') !== false) {
            return true;
        } elseif (strpos($user_agent, 'baidu') !== false) {
            return true;
        } elseif (strpos($user_agent, 'googlebot') !== false) {
            return true;
        }

        $d = get_cookie("is_scrapy");
        if ($d != $this->key) {
            response()->redirectTo("/")->send();
            abort(404);
        }
    }
}

?>

